/*
* @Date: 2021/3/6
* @Author: XueChengwu <xuechengwu@erayt.com>
* @Copyright: 2015-2019 Erayt, Inc.
* @Description: If you have some questions, please contact: xuechengwu@erayt.com.
*/
import Markvo from '../brain/markvo';


self.addEventListener('message', (e) => {
  function distEclud(vecA,vecB){
    var sum = 0;
    for(var i = 0;i < vecA.length;i++){
      var deta = vecA[i] - vecB[i];
      sum = sum + deta * deta;
    }
    return Math.sqrt(sum);
  }
  let { vector, kmeans } = e.data;
  if (!kmeans) {
    self.postMessage({
      result: vector,
    });
    return;
  }
  kmeans = JSON.parse(kmeans);
  const { centroids, markvo } = kmeans;
  let minIndex = 0;
  let minDist = Number.MAX_VALUE;
  for (let i = 0; i < centroids.length; i++) {
    const dist = distEclud(vector, centroids[i]);
    if (dist < minDist) {
      minDist = dist;
      minIndex = i;
    }
  }
  const mak = new Markvo(centroids.length, markvo);
  const { nextState, nextProp } = mak.cast(minIndex);
  const avgCenter = [];
  for (let i = 0; i < centroids[0].length; i++) {
    if (avgCenter[i] === undefined) {
      avgCenter[i] = 0;
    }
    for (let j = 0; j < centroids.length; j++) {
      avgCenter[i] += centroids[j][i] * nextProp[j];
    }
  }
  self.postMessage({
    result: centroids[nextState],
    avgCenter,
  });
});
